{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Simhash文档相似度计算（去重）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [],
   "source": [
    "import jieba\n",
    "import jieba.analyse\n",
    "from collections import Counter"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1、定义一个分词功能的函数."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def word_segmentation(strings):\n",
    "    '''\n",
    "        利用结巴工具对文本进行分词，并返回单词的权重.\n",
    "    '''\n",
    "    # 分词，返回一个单词列表\n",
    "    tokens = jieba.lcut(strings)\n",
    "    \n",
    "    # 计算每个单词的权值(使用词频)\n",
    "    weights_dcit = dict(Counter(tokens))\n",
    "    \n",
    "    return tokens, weights_dcit\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2、定义一个Simhash，提供对文档的数值映射和文档间相似度计算的功能."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "24     0.26642211074157\n",
      "13     2.8808327266833885e-05\n"
     ]
    }
   ],
   "source": [
    "class Simhash(object):\n",
    "    \n",
    "    # 初始化函数\n",
    "    def __init__(self, weights_dict, tokens='', hashbits=64):\n",
    "        self.hashbits = hashbits\n",
    "        self.hash = self.simhash_function(tokens, weights_dict)\n",
    "    \n",
    "    # toString函数\n",
    "    def __str__(self):\n",
    "        return str(self.hash)\n",
    "    \n",
    "    \n",
    "    # 给每一个单词生成对应的hash值\n",
    "    def _string_hash(self, source):\n",
    "        if source == '':\n",
    "            return 0\n",
    "        else:\n",
    "            x = ord(source[0]) << 7\n",
    "            m = 1000003\n",
    "            mask = 2 ** self.hashbits - 1\n",
    "            for c in source:\n",
    "                x = ((x * m) ^ ord(c)) & mask\n",
    "            x ^= len(source)\n",
    "            if x == -1:\n",
    "                x = -2\n",
    "            return x\n",
    "        \n",
    "    \n",
    "    # 生成simhash值\n",
    "    def simhash_function(self, tokens, weights_dict):\n",
    "        v = [0] * self.hashbits\n",
    "        for key, t in {x: self._string_hash(x) for x in tokens}.items():\n",
    "            for i in range(self.hashbits):\n",
    "                bitmask = 1 << i\n",
    "                if t & bitmask:\n",
    "                    v[i] += weights_dict[key]\n",
    "                else:\n",
    "                    v[i] -= weights_dict[key]\n",
    "        \n",
    "        fingerprint = 0\n",
    "        for i in range(self.hashbits):\n",
    "            if v[i] >= 0:\n",
    "                fingerprint += 1 << i\n",
    "        return fingerprint\n",
    "    \n",
    "    \n",
    "    # 求文档间的海明距离\n",
    "    def hamming_distance(self, other):\n",
    "        x = (self.hash ^ other.hash) & ((1 << self.hashbits) - 1 )\n",
    "        tot = 0\n",
    "        while x :\n",
    "            tot += 1\n",
    "            x &= x - 1\n",
    "        return tot\n",
    "    \n",
    "    \n",
    "    #求相似度\n",
    "    def similarity(self, other):\n",
    "        a = float(self.hash)\n",
    "        b = float(other.hash)\n",
    "        if a > b:\n",
    "            return b / a\n",
    "        else: \n",
    "            return a / b\n",
    "        \n",
    "\n",
    "    \n",
    "if __name__ == '__main__':\n",
    "    \n",
    "    s1 = '你好我是新来的，请多多关照。'\n",
    "    tokens1, weights_dcit1 = word_segmentation(s1)\n",
    "    hash1 = Simhash(weights_dict=weights_dcit1, tokens=tokens1)\n",
    "    \n",
    "    s2 = '为什么大家觉得你没有那么大的脾气呢.'\n",
    "    tokens2, weights_dcit2 = word_segmentation(s2)\n",
    "    hash2 = Simhash(weights_dict=weights_dcit2, tokens=tokens2)\n",
    "    \n",
    "    s3 = '你好我来自北京，请多多关照。'\n",
    "    tokens3, weights_dcit3 = word_segmentation(s3)\n",
    "    hash3 = Simhash(weights_dict=weights_dcit3, tokens=tokens3)\n",
    "    \n",
    "    print(hash1.hamming_distance(hash2) , \"   \" , hash1.similarity(hash2))\n",
    "    print(hash1.hamming_distance(hash3) , \"   \" , hash1.similarity(hash3))    "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
